package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
@Slf4j
public class UserInfoService {
    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    public boolean saveUserInfo(Map<String, String> param, String token) {

        // 校验mapper
        User user = this.userService.queryUserByToken(token);

        if (null == user){
            return false;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsAnyIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));
        return userInfoMapper.insert(userInfo) ==1 ;

    }


    /**
     *  完善用户信息 -- 保存用户头像
     * @param file
     * @param token
     * @return
     */
    public Boolean saveUserLogo(MultipartFile file, String token) {

        // 校验token
        User user = this.userService.queryUserByToken(token);
        // 不存在
        if (null == user){
            return false;
        }

        // 存在  就校验是否为人像
        try {
            boolean flag = this.faceEngineService.checkIsPortrait(file.getBytes());
            // 不是人像 就返回false
            if ( !flag ){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 是人像 就需要保存在到阿里云的 oss
        PicUploadResult result = this.picUploadService.upload(file);
        // 判断一下是否上传成功
        if (StringUtils.isEmpty(result.getName())){
            // 上传失败
            return false;
        }
        // 上传成功 需要把头像保存到用户信息表中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());

        return this.userInfoMapper.update(userInfo,queryWrapper) !=0 ;
    }
}
